// pages/repairdetails/repairdetails.ts
import {
  orderDetail,
  chargeBack,
  isClockin,
  stewardOrder,
  searchMaintainer,
  maintenanceList,
  updateIsRead
} from "../../../api/order";
const dayjs = require("../../../utils/day");
const day = dayjs();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    data: {},
    list: [],
    grzt: "",
    jfzt: "",
    fjwd: "",
    sdwd: "",
    fmzt: "",
    jswd: "",
    hswd: "",
    adress: "",
    userid: -1,
    houseID: -1,
    position: "",
    pdid: -1,
    lat: "",
    log: "",
    show: false,
    isPicker: false,
    username: "",
    columns: [],
    beforeClose: null,
    repairReasonId: -1,
    repairReasonName: "",
    radio: "1",
    isDialog: false,
    onBeforeClose: (action: any) => {
      return true;
    },
    revokeReason:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option: any) {
    const comID = wx.getStorageSync("userInfo").data.comID;
    orderDetail(comID, option.id).then((res: any) => {
      console.log(res);
      if (res.data.code == 200)
        this.setData({
          data: res.data.data,
          grzt: res.data.data.供热状态,
          jfzt: res.data.data.住户缴费状态,
          fjwd: res.data.data.房间温度,
          sdwd: res.data.data.设定温度,
          fmzt: res.data.data.阀门状态,
          jswd: res.data.data.进水温度,
          hswd: res.data.data.回水温度,
        });
      const address = res.data.data.address;
      const parts = address.split(",");
      this.setData({
        lat: parts[0],
        log: parts[1],
      });
      this.reverseGeocode(parts[0], parts[1]);
      maintenanceList(res.data.data.houseID, comID).then((e: any) => {
        this.setData({
          list: e.data,
        });
      });
    });

    this.setData({
      pdid: option.id,
    });
    updateIsRead(comID,option.id)
  },
  reverseGeocode(latitude: string, longitude: string) {
    const apiKey = "YvSi5eCAVD6v3Z0OUeqjdF0oYQcnK7gt"; // 替换为你的百度地图API密钥（AK）
    const apiUrl = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${apiKey}&output=json&coordtype=wgs84ll&location=${longitude},${latitude}`;
    wx.request({
      url: apiUrl,
      success: (res: any) => {
        if (res.data.status === 0) {
          const address = res.data.result.formatted_address;
          this.setData({
            adress: address,
          });
          console.log("地址：", address);
          // 在这里处理地址信息，例如更新页面上的文本或执行其他操作
        } else {
          console.error("逆地址解析失败：", res.data.message);
        }
      },
      fail: (error) => {
        console.error("请求失败：", error);
      },
    });
  },
  onCall() {
    const { userTel } = this.data.data;
    if (userTel) {
      wx.makePhoneCall({
        phoneNumber: userTel,
      });
    } else {
      wx.showModal({
        title: "提示",
        showCancel: false,
        content: "暂无用户电话",
        success(res) {},
      });
    }
  },
  onClickLeft() {
    wx.navigateBack({
      delta: 1,
    });
  },
  onBack() {
    const comID = wx.getStorageSync("userInfo").data.comID;
    const that = this;
    this.setData({
      isDialog: true,
    });
    // wx.showModal({
    //   title: "提示",
    //   content: "你要退单到客服还是管家?",
    //   cancelText: "客服",
    //   confirmText: "管家",
    //   success(res: any) {
    //     if (res.confirm) {
    //   chargeBack(comID, that.data.pdid, that.data.userid, 0)
    //     .then((res: any) => {
    //       if (res.data.code == 200) {
    //         wx.showToast({
    //           title: "退单成功",
    //           icon: "success",
    //           success: () => {
    //             wx.navigateBack({
    //               delta: 1,
    //             });
    //           },
    //         });
    //       } else {
    //         wx.showToast({
    //           title: "退单失败",
    //           icon: "error",
    //         });
    //       }
    //     })
    //     .catch((err) => {
    //       wx.showToast({
    //         title: "退单失败",
    //         icon: "error",
    //       });
    //     });
    //     } else {
    //       chargeBack(comID, that.data.pdid, that.data.userid, 1)
    //         .then((res: any) => {
    //           if (res.data.code == 200) {
    //             wx.showToast({
    //               title: "退单成功",
    //               icon: "success",
    //               success: () => {
    //                 wx.navigateBack({
    //                   delta: 1,
    //                 });
    //               },
    //             });
    //           } else {
    //             wx.showToast({
    //               title: "退单失败",
    //               icon: "error",
    //             });
    //           }
    //         })
    //         .catch((err) => {
    //           wx.showToast({
    //             title: "退单失败",
    //             icon: "error",
    //           });
    //         });
    //     }
    //   },
    // });
  },
  onClose() {
    this.setData({
      isDialog: false,
    });
  },
  onSubmit() {
    const comID = wx.getStorageSync("userInfo").data.comID;
    const that = this;
    const isDialog = that.data.isDialog;
    const radio = that.data.radio;
    const revokeReason = that.data.revokeReason
    if (isDialog) {
      that.setData({
        onBeforeClose: (action) => {
          if (action === "confirm") {
            console.log(radio);
            if (radio == 1) {
                if(revokeReason){
                    chargeBack(comID, that.data.pdid, that.data.userid, 1,revokeReason)
                    .then((res: any) => {
                      if (res.data.code == 200) {
                        wx.showToast({
                          title: "退单成功",
                          icon: "success",
                          success: () => {
                            wx.navigateBack({
                              delta: 1,
                            });
                            return true;
                          },
                        });
                      } else {
                        wx.showToast({
                          title: "退单失败",
                          icon: "error",
                        });
                        return false;
                      }
                    })
                    .catch((err) => {
                      wx.showToast({
                        title: "退单失败",
                        icon: "error",
                      });
                      return false;
                    });
                }else{
                    wx.showToast({
                        title:'缺少原因',
                        icon:'error'
                    })
                }
            } else {
                if(revokeReason){
                    chargeBack(comID, that.data.pdid, that.data.userid, 0,revokeReason)
                    .then((res: any) => {
                      if (res.data.code == 200) {
                        wx.showToast({
                          title: "退单成功",
                          icon: "success",
                          success: () => {
                            wx.navigateBack({
                              delta: 1,
                            });
                            return true;
                          },
                        });
                      } else {
                        wx.showToast({
                          title: "退单失败",
                          icon: "error",
                        });
                        return false;
                      }
                    })
                    .catch((err) => {
                      wx.showToast({
                        title: "退单失败",
                        icon: "error",
                      });
                      return false;
                    });
                }else{
                    wx.showToast({
                        title:'缺少原因',
                        icon:'error'
                    })
                }
            }
          }
          return false;
        },
      });
      return;
    }
  },
  onSignin() {
    const { lat, log } = this.data;
    const { house, id } = this.data.data;
    wx.navigateTo({
      url:
        "/subpackagesA/pages/clockin/clockin?lat=" +
        lat +
        "&log=" +
        log +
        "&house=" +
        house +
        "&id=" +
        id,
    });
  },
  onProcessor(e: any) {
    console.log(e);
    const time = dayjs().format("YYYY-MM-DD");
    const { id } = e.currentTarget.dataset;
    console.log(time);
    const comID = wx.getStorageSync("userInfo").data.comID;
    // wx.navigateTo({
    //   url: "/subpackagesA/pages/processor/processor?id=" + id,
    // });
    isClockin(comID, id, time).then((res: any) => {
      if (comID == 14) {
        wx.navigateTo({
          url: "/subpackagesA/pages/processor/processor?id=" + id,
        });
      } else {
        if (res.data.code == 200) {
          wx.navigateTo({
            url: "/subpackagesA/pages/processor/processor?id=" + id,
          });
        } else {
          wx.showModal({
            title: "错误",
            content: res.data.message,
          });
        }
      }
    });
  },
  handldeClose() {
    this.setData({
      show: false,
    });
  },
  onPickerClose() {
    this.setData({
      isPicker: false,
    });
  },
  onSend() {
    const comID = wx.getStorageSync("userInfo").data.comID;
    const userID = wx.getStorageSync("userInfo").data.userID;
    this.setData({
      show: true,
    });
    searchMaintainer(comID, userID).then((res: any) => {
      this.setData({
        columns: res.data,
      });
      console.log(res);
    });
  },
  handleInput() {
    this.setData({
      isPicker: true,
    });
  },
  handleSubmit() {
    const username = this.data.username;
    this.setData({
      beforeClose: (action) => {
        new Promise((resolve) => {
          if (action === "confirm") {
            console.log(username);
            if (username == "") {
              wx.showToast({
                icon: "error",
                title: "维修工未选",
              });
              resolve(false);
            }
          } else {
            resolve(true);
          }
        });
      },
    });
    if (username != "") {
      const comID = wx.getStorageSync("userInfo").data.comID;
      const userID = wx.getStorageSync("userInfo").data.userID;
      const repairPersonID = this.data.repairReasonId;
      const repairReasonName = this.data.repairReasonName;
      const orderID = this.data.pdid;
      stewardOrder(
        comID,
        userID,
        repairPersonID,
        orderID,
        repairReasonName
      ).then((res: any) => {
        if (res.data.code == 200) {
          wx.showToast({
            title: "派单成功",
          });
          wx.navigateBack({
            delta: 1,
          });
        } else {
          wx.showToast({
            icon: "error",
            title: "派单失败",
          });
        }
        console.log(res);
      });
      this.setData({
        show: false,
      });
    }
  },
  onPicker(e) {
    this.setData({
      username: e.detail.value.repairReason,
      repairReasonId: e.detail.value.id,
      repairReasonName: e.detail.value.repairReason,
      isPicker: false,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userid: wx.getStorageSync("userInfo").data.userID,
      position: wx.getStorageSync("userInfo").data.position,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
